const mongoose = require("./../db");
const Schema = mongoose.Schema;

const schema = new Schema({
  // 上级部门ID，引用自身模型
  parentId: { type: Schema.Types.ObjectId, ref: 'Department' },
  // 部门名称
  name: { type: String, required: true },
  // 部门编号
  code: { type: String, required: true, unique: true },
  // 显示排序
  sort: { type: Number, default: 0 },
  // 部门状态：0禁用 1启用
  status: { type: Number, default: 1 }
});

schema.statics.buildTree = function(departments, parentId = null,parentName = null) {
  console.log('1-buildTree');
  console.log('2-查找 ',parentId,parentName,'的孩子节点');
  const result = [];
  const children = departments.filter((dept,index) => 
    
    {
      // console.log('3-',dept.parentId.toString(),parentId);
      // return dept.parentId.toString() === parentId;
    
      return dept.parentId?._id == parentId;
    }
  )
  console.log('4-孩子节点有',children.length,'个');
  // console.log('departments',departments.length,JSON.stringify(departments))  
  for (const child of children) {
    const node = {
      ...child._doc,
      children: this.buildTree(departments, child._id.toString(),child.name)
    };
    result.push(node);
  }
  
  return result;
};

module.exports = mongoose.model("Department", schema);